﻿/*******************************************************
*类名称：MemberInfoManager
*版本号：V1.0.0.0
*作者：成俊杰
*CLR版本：4.0.30319.36264
*创建时间：2017-08-17 10:57:03
*说明：T_MemberInfo管理类
*更新备注：
**********************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Wechat.Dao;
using Wechat.Domain;
using Wechat.Util.JsonHelp;
using Wechat.Util.WechatUtil;

namespace Wechat.Manager.Implement
{
    /// <summary>
    /// T_MemberInfo
    /// </summary>
    public class MemberInfoManager : GenericManagerBase<MemberInfo>, IMemberInfoManager
    {
        public IWechatTokenManager WechatTokenManager { get; set; }

        /// <summary>
        /// 创建会员通过微信OpenId
        /// </summary>
        /// <returns></returns>
        public void CreateMemberInfoByOpenId(string openId)
        {
            //获取Token
            string AccessToken = WechatTokenManager.GetAccessToken();

            //新会员关注事件，需要新建会员信息
            //从微信获取客人基本信息
            string response = WechatMsgUtil.PostData("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + AccessToken + "&openid=" + openId + "&lang=zh_CN", "");
            DataTable mbdt = JsonDataTable.JsonToDataTable(response);
            var WxOpenId = mbdt.Rows[0]["openid"].ToString().Trim();

            //需要判断是否存在重复微信openid
            var result = GetByKey("T_MemberInfo", "WxOpenId", WxOpenId).FirstOrDefault();

            if (result == null)
            {
                //创建新会员
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.WxOpenId = WxOpenId;
                memberInfo.WxNikeName = mbdt.Rows[0]["nickname"].ToString().Trim();
                memberInfo.WxSex = Convert.ToInt32(mbdt.Rows[0]["sex"].ToString().Trim());
                memberInfo.WxAttention = DateTime.Now;
                memberInfo.RoleIds = "0";
                memberInfo.WxAddress = mbdt.Rows[0]["country"].ToString().Trim() + "-" + mbdt.Rows[0]["province"].ToString().Trim() + "-" + mbdt.Rows[0]["city"].ToString().Trim();
                memberInfo.WxDescption = response;
                //创建新会员
                 Insert(memberInfo);
            }
        }
    }
}